<!doctype html>
<html>
  <head>
    <title>axios - get example</title>
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/>
  </head>
  <body class="container">
    <h1>axios.get</h1>
    <ul id="people" class="list-unstyled"></ul>

    <button id="cancel">
      cancel
    </button>

    <script src="/axios.min.js"></script>
    <script>
      // 取消文档 https://github.com/axios/axios#cancellation
      const CancelToken = axios.CancelToken;
      const source = CancelToken.source();
      function sendRequest(){
        axios.get('/get/server', {
          cancelToken: source.token
        })
          .then(function (response) {
            document.getElementById('people').innerHTML = response.data.map(function (person) {
              return (
                '<li class="row">' +
                  '<img src="https://avatars.githubusercontent.com/u/' + person.avatar + '?s=50" class="col-md-1"/>' +
                  '<div class="col-md-3">' +
                    '<strong>' + person.name + '</strong>' +
                    '<div>Github: <a href="https://github.com/' + person.github + '" target="_blank">' + person.github + '</a></div>' +
                    '<div>Twitter: <a href="https://twitter.com/' + person.twitter + '" target="_blank">' + person.twitter + '</a></div>' +
                  '</div>' +
                '</li><br/>'
              );
            }).join('');
          })
          .catch(function (err) {
            document.getElementById('people').innerHTML = '<li class="text-danger">' + err.message + '</li>';
            if (axios.isCancel(err)) {
              console.log('Request canceled', err.message);
            } else {
              // handle error
            }
          });
      }
      const timer = setTimeout(() => {
        console.log('sendRequest');
        sendRequest();
        clearTimeout(timer);
      }, 5000);

      document.getElementById('cancel').addEventListener('click', function(){
        console.log('cancel button');
        // cancel the request (the message parameter is optional)
        source.cancel('哎呀，我被若川取消了');
      });
    </script>
  </body>
</html>
